package com.study.zookeeper.curator;

import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.leader.LeaderSelector;
import org.apache.curator.framework.recipes.leader.LeaderSelectorListenerAdapter;
import org.apache.curator.retry.ExponentialBackoffRetry;

public class MasterSelectCurator {

    private static String connectStr = "127.0.0.1:2181,127.0.0.1:2182,127.0.0.1:2184";
    private static RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
    private static String path= "/zlx";
    private static CuratorFramework client = CuratorFrameworkFactory
            .builder()
            .connectString(connectStr)
            .sessionTimeoutMs(5000)
            .retryPolicy(retryPolicy)
            //指定命名空间
            // .namespace("")
            .build();

    public static void main(String[] args) throws Exception{

        client.start();
        LeaderSelector selector = new LeaderSelector(client, path, new LeaderSelectorListenerAdapter() {
            public void takeLeadership(CuratorFramework curatorFramework) throws Exception {
                System.out.println("成为Master角色");
                Thread.sleep(3000);
                System.out.println("完成Master操作，释放Master特权");
            }
        });
        selector.autoRequeue();
        selector.start();
        Thread.sleep(Integer.MAX_VALUE);
    }
}
